package cn.iocoder.yudao.module.erp.service.warningrules;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.erp.controller.admin.warningrules.vo.WarningRulesPageReqVO;
import cn.iocoder.yudao.module.erp.controller.admin.warningrules.vo.WarningRulesSaveReqVO;
import cn.iocoder.yudao.module.erp.dal.dataobject.warningrules.WarningRulesDO;
import cn.iocoder.yudao.module.erp.dal.mysql.warningrules.WarningRulesMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.erp.enums.ErrorCodeConstants.WARNING_RULES_NOT_EXISTS;

/**
 * ERP 预警规则 Service 实现类
 *
 * @author 源码
 */
@Service
@Validated
public class WarningRulesServiceImpl implements WarningRulesService {

    @Resource
    private WarningRulesMapper warningRulesMapper;

    @Override
    public Long createWarningRules(WarningRulesSaveReqVO createReqVO) {
        // 插入
        WarningRulesDO warningRules = BeanUtils.toBean(createReqVO, WarningRulesDO.class);
        warningRulesMapper.insert(warningRules);
        // 返回
        return warningRules.getId();
    }

    @Override
    public void updateWarningRules(WarningRulesSaveReqVO updateReqVO) {
        // 校验存在
        validateWarningRulesExists(updateReqVO.getId());
        // 更新
        WarningRulesDO updateObj = BeanUtils.toBean(updateReqVO, WarningRulesDO.class);
        warningRulesMapper.updateById(updateObj);
    }

    @Override
    public void deleteWarningRules(Long id) {
        // 校验存在
        validateWarningRulesExists(id);
        // 删除
        warningRulesMapper.deleteById(id);
    }

    private void validateWarningRulesExists(Long id) {
        if (warningRulesMapper.selectById(id) == null) {
            throw exception(WARNING_RULES_NOT_EXISTS);
        }
    }

    @Override
    public WarningRulesDO getWarningRules(Long id) {
        return warningRulesMapper.selectById(id);
    }

    @Override
    public PageResult<WarningRulesDO> getWarningRulesPage(WarningRulesPageReqVO pageReqVO) {
        return warningRulesMapper.selectPage(pageReqVO);
    }

}